/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

import tal.drivechain.chain.ChainNode;
import tal.drivechain.chain.script.ScriptCommand;
import tal.drivechain.plugin.Channel;
import tal.drivechain.variable.Variable;

/**
 *
 * @author eisental
 */
public class SendCommand extends ShellCommand {

    public SendCommand(DriveShell shell) { super(shell); }

    private static final String[] commandList = new String[] { "send <node-name> <variable>" };

    @Override
    public boolean runCommand(ScriptCommand command) throws IllegalArgumentException {
        if (command.getName().equals("send")) {
            if (!shell.getActiveChain().isRunning())
                throw new IllegalArgumentException("Can't send variable while chain is closed.");
            if (command.getArgCount()!=3)
                throw new IllegalArgumentException("Invalid syntax (should be: send global/<instance name> <variable>");

            Variable message = Variable.parseVariable("fromShell", null, command.getArg2(), false);
            if (message.isEvaluateAtHome()) message = message.evaluate(shell.getActiveChain());

            if (command.getArg1().equals("global")) {
                shell.getActiveChain().getVarTable().sendGlobalMessage(message);
            } else {
                ChainNode n = shell.getActiveChain().getNodeByPath(command.getArg1());
                if (n==null)
                    throw new IllegalArgumentException("Node " + command.getArg1() + " doesn't exist in chain " + shell.getActiveChain().getName());

                out.println("Sending message " + message + " to " + n.getName());
                n.send(message, -1, Channel.CHAIN);
            }

            return true;
        } else return false;
    }

    @Override
    public String[] getCommands() {
        return commandList;
    }

}
